package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"goods-mgt-sys/cache"
	"goods-mgt-sys/model"
	"goods-mgt-sys/pck"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{"code": 500, "msg": "数据不能为空"})
		return
	}
	redis_key := "login_error_" + username
	errCout, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCout >= 3 {
		c.JSON(200, gin.H{"code": 500, "msg": "禁止登录"})
		return
	}
	var user model.User
	err := model.DB.Where("username=?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": "查询失败"})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{"code": 500, "msg": "用户名不存在"})
		return
	}
	if user.Password != pck.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCout == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{"code": 500, "msg": "密码错误"})
			return
		} else {
			c.JSON(200, gin.H{"code": 500, "msg": "密码错误"})
			return
		}
	}
	c.JSON(200, gin.H{"code": 200, "msg": "登录成功"})
	return
}
func Search(c *gin.Context) {
	id := c.Query("id")
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var good model.Good
	redis_key := "data_id" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Where("id=?", id).Offset(offset).Limit(size).Find(&good)
		jsonData, _ := json.Marshal(&good)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &good)
	}
	c.JSON(200, gin.H{"code": 200, "msg": "查询成功", "data": good})
	return
}
func Comment(c *gin.Context) {
	comments := c.PostForm("comments")
	comment := model.Comment{
		Comments: comments,
	}
	model.DB.Create(&comment)
	var com model.Comment
	redis_key := "comment_id" + strconv.Itoa(int(comment.ID))
	model.DB.Where("id=?", comment.ID).Find(&com)
	jsonData, _ := json.Marshal(&com)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{"code": 200, "msg": "添加成功"})
	return
}
func CommentList(c *gin.Context) {

	var comment []model.Comment
	redis_key := "list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Find(&comment)
		jsonData, _ := json.Marshal(&comment)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &comment)
	}
	c.JSON(200, gin.H{"code": 200, "msg": "查询成功", "data": comment})
	return
}
